package com.erp.erp_mask.config;



import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.erp.erp_mask.mapper.TPermissionsMapper;
import com.erp.erp_mask.mapper.TUsersMapper;
import com.erp.erp_mask.pojo.TUsers;
import jakarta.annotation.Resource;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @BelongsProject: erp_mask
 * @BelongsPackage: com.erp.erp_mask.config
 * @Author: wang
 * @CreateTime: 2024-05-08  10:56
 * @Description: TODO
 * @Version: 1.0
 * @effect:
 */
@Component
public class DbUserDetailService implements UserDetailsService {
    @Resource
    private TUsersMapper usersMapper;
    @Resource
    private TPermissionsMapper permissionsMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<TUsers> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(TUsers::getUserName, username);
        TUsers tUsers = usersMapper.selectOne(wrapper);
        if (tUsers == null) {
            throw new RuntimeException("对不起,用户名或密码错误!");
        }
        List<String> list = permissionsMapper.selectPermCodeList(tUsers.getRoleId());
        String[] arr = list.stream().toArray(String[]::new);
        UserDetails userDetails = User
                .withUsername(tUsers.getUserName())
                .password(tUsers.getUserPassword())
                .authorities(arr)
                .build();
        return userDetails;
    }
}
